﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Diagnostics;
using personalplaner.business.dienstplan;

namespace personalplaner.common.controls
{
    public class DiensteDataGrid : DataGrid
    {
        public DiensteDataGrid()
        {
        }

        public DataTemplateSelector CellTemplateSelector
        {
            get { return (DataTemplateSelector)GetValue(CellTemplateSelectorProperty); }
            set { SetValue(CellTemplateSelectorProperty, value); }
        }

        public static readonly DependencyProperty CellTemplateSelectorProperty =
            DependencyProperty.Register("Selector", typeof(DataTemplateSelector), typeof(DiensteDataGrid),
            new FrameworkPropertyMetadata(null));



        protected override void OnAutoGeneratingColumn(DataGridAutoGeneratingColumnEventArgs e)
        {
            e.Cancel = true;
            Columns.Add(new DataGridPlanItemTemplateColumn
            {
                Header = e.Column.Header,
                CellTemplateSelector = CellTemplateSelector
            });
        }

        protected override void OnItemsSourceChanged(System.Collections.IEnumerable oldValue, System.Collections.IEnumerable newValue)
        {
            base.OnItemsSourceChanged(oldValue, newValue);

            Trace.WriteLine(newValue is IList<IList<PlanItem>>);
            CreateColumns(newValue as IList<IList<PlanItem>>);
        }

        private void CreateColumns(IList<IList<PlanItem>> items)
        {
            if (items == null)
                throw new ArgumentException("ItemsSource has to be of type IList<IList<PlanItem>>", "items");

            Columns.Clear();

            int index = 0;
            foreach (var itm in items[0])
            {
                var col = new DataGridPlanItemTemplateColumn
                {
                    IsReadOnly = true,
                    CanUserReorder = false,

                    Header = itm.Datum.Day,

                    ColumnName = string.Format("[{0}]", index),
                    CellTemplateSelector = CellTemplateSelector
                    //CellTemplate = celltemplate
                };

                index++;
                Columns.Add(col);
            }
        }
    }
}
